import Layout from '@/common/layout/index.vue'
import {createRouter, createWebHistory} from "vue-router";

//全部组件路径
let components = import.meta.glob("@/module/**/*.vue")
//相对路径
const BASE = '/src/module';

// 公共路由
export const constantRouter = [
    {
        path: '/redirect',
        component: Layout,
        hidden: true,
        children: [
            {
                path: '/redirect/:path(.*)',
                component: () => import('@/module/common/index.vue'),
                meta: {title: '重定向'}
            }
        ]
    },
    {
        path: '/login',
        component: () => import('@/module/login.vue'),
        hidden: true,
        meta: {title: '登录'}
    },
    {
        path: '/register',
        component: () => import('@/module/register.vue'),
        hidden: true,
        meta: {title: '注册'}
    },
    {
        path: '',
        component: Layout,
        name: "Layout",
        redirect: '/index',
        children: [
            {
                path: '/index',
                component: () => import('@/module/sys/sysMenu.vue'),
                name: 'Index',
                meta: {title: '首页'}
            },
            {
                path: '/401',
                component: () => import('@/module/common/401.vue'),
                hidden: true,
                meta: {title: '权限不足'}

            },
            {
                path: "/:pathMatch(.*)*",
                component: () => import('@/module/common/404.vue'),
                hidden: true,
                meta: {title: '页面不存在'}
            },

        ]
    },
]

//异步加载路由组件
export function asyncAddRouter(routeList) {
    // //console.log(components)
    return new Promise((resolve, reject) => {

        routeList.filter(item => {
            if (item.routePath && item.filePath) {
                let component = components[`${BASE}${item.filePath}.vue`]
                //console.log(common)
                //插入动态路由
                router.addRoute("Layout", {
                    name: item.routePath,
                    path: item.routePath,
                    component: component,
                    meta: {title: item.name}
                })
            }
        })
        resolve(true)
    })
}

const router = createRouter({
    history: createWebHistory(),
    routes: constantRouter,
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return {top: 0}
        }
    },
});

export default router;
